package server

import (
	"bytes"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/disintegration/imaging"

	"github.com/chai2010/webp"

	"github.com/nfnt/resize"
	log "github.com/sjqzhang/seelog"
)

func (c *Server) ResizeImageByBytes(w http.ResponseWriter, data []byte, width, height uint) {
	var (
		img     image.Image
		err     error
		imgType string
	)
	reader := bytes.NewReader(data)
	img, imgType, err = image.Decode(reader)
	if err != nil {
		log.Error(err)
		return
	}
	fmt.Println(width, height)
	img = resize.Resize(width, height, img, resize.Lanczos3)
	if imgType == "jpg" || imgType == "jpeg" {
		jpeg.Encode(w, img, nil)
	} else if imgType == "png" {
		png.Encode(w, img)
	} else {
		w.Write(data)
	}
}

func (c *Server) ResizeImage(w http.ResponseWriter, fullpath string, width, height uint) {

	fmt.Println("图片完整路径", fullpath)

	fileName := filepath.Base(fullpath)

	name := strings.TrimSuffix(fileName, filepath.Ext(fileName)) //老文件名

	newFileName := fmt.Sprintf("%s%d%d", name, width, height) //新文件名

	dir := filepath.Dir(fullpath) //存储路径

	ext := filepath.Ext(fullpath) //文件拓展名

	newPath := fmt.Sprintf("%s/%s_zoom%s", dir, newFileName, ".webp")

	// 若已经处理直接返回
	data, err := os.Open(newPath)
	if err == nil {
		defer data.Close()
		fmt.Println("已处理图片直接返回")
		//w.Write(data)
		io.Copy(w, data)
		return
	}

	var src image.Image

	if ext == "webp" {

		data, _ := os.ReadFile(fullpath)
		src, err = webp.Decode(bytes.NewReader(data))
		if err != nil {
			fmt.Println("打开webp图片失败", err)
		}
	} else {

		src, err = imaging.Open(fullpath)
		if err != nil {
			fmt.Println("打开图片失败", err)
		}

	}

	// 缩放到宽 800，高度等比缩放（height=0 表示自动保持比例）

	/**
		参数	效果	速度	说明
	imaging.NearestNeighbor	最快	🚀 极快	质量低，锯齿严重，适合缩略图
	imaging.Linear	快	🚀 快	比 Nearest 好一些，质量仍一般
	imaging.Box	中等	⚖️ 中	速度与质量平衡，常用于缩小图像
	imaging.CatmullRom	高质量	🐢 较慢	默认值，质量好，速度一般
	imaging.Lanczos	极高质量	🐢 最慢	缩小时质量最好（推荐）
	imaging.Gaussian	模糊效果	❌ 慎用	适用于特殊需求
	imaging.MitchellNetravali	较高质量	🐢	类似 CatmullRom，平滑过渡

	*/
	dst := imaging.Resize(src, int(width), int(height), imaging.Linear)

	//转webp
	webpBytes, errs := webp.EncodeRGBA(dst, 50)
	if errs != nil {
		fmt.Println("转webp失败", err)
		return
	}

	//保存webp文件
	if err = os.WriteFile(newPath, webpBytes, 0666); err != nil {
		fmt.Println("图片写入新文件webp失败", err)
		return
	}

	fmt.Println("图片转webp缩放成功并保存成功")

	io.Copy(w, bytes.NewBuffer(webpBytes))

}
